package com.zq.mycloud.gateway.filter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.zq.mycloud.core.respones.GeneralResult;
import com.zq.mycloud.core.consts.ErrorCodeConstant;
import com.zq.mycloud.gateway.util.I18nUtil;
import lombok.extern.slf4j.Slf4j;
import org.reactivestreams.Publisher;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.route.Route;
import org.springframework.cloud.gateway.support.ServerWebExchangeUtils;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.http.server.reactive.ServerHttpResponseDecorator;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/**
 * @author ：zhang qiang
 * @package :com.zq.mycloud.gateway.filter
 * @date ：Created in 2020/11/20 下午10:50
 * @description：
 * @modified By：
 * @version: $
 */
@Component
@Slf4j
public class RequestGlobalFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpResponse originalResponse = exchange.getResponse();
        DataBufferFactory bufferFactory = originalResponse.bufferFactory();
        ServerHttpResponseDecorator decoratedResponse = new ServerHttpResponseDecorator(originalResponse) {
            @Override
            public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
                if (body instanceof Flux) {
                    Flux<? extends DataBuffer> fluxBody = (Flux<? extends DataBuffer>) body;
                    if (getStatusCode().equals(HttpStatus.OK)) {

                        return super.writeWith(fluxBody.map(dataBuffer -> {
                            byte[] content = new byte[dataBuffer.readableByteCount()];
                            dataBuffer.read(content);
                            //释放掉内存
                            DataBufferUtils.release(dataBuffer);
                            //原始响应
                            String originalBody = new String(content, Charset.forName("UTF-8"));
                            //修改后的响应体
                            GeneralResult responseResult = JSON.parseObject(originalBody, GeneralResult.class);
                            responseResult.setMessage(I18nUtil.translateCode(responseResult.getCode()));
                            return bufferFactory.wrap(JSON.toJSONString(responseResult).getBytes());
                        }));
                    } else {
                        return super.writeWith(fluxBody.map(dataBuffer -> {
                            Route route = (Route) exchange.getAttributes().get(ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR);
                            String routeId = route == null ? "" : route.getId();
                            GeneralResult errorResponse = new GeneralResult();
                            errorResponse.setCode(ErrorCodeConstant.REQUESTED_SERVICE_INTERNAL_ERROR);
                            String message = I18nUtil.translateCode(ErrorCodeConstant.REQUESTED_SERVICE_INTERNAL_ERROR, routeId);
                            errorResponse.setMessage(message);
                            byte[] uppedContent = JSON.toJSONString(errorResponse, SerializerFeature.WriteMapNullValue).getBytes(StandardCharsets.UTF_8);
                            originalResponse.getHeaders().setContentLength(uppedContent.length);
                            setStatusCode(HttpStatus.OK);
                            return bufferFactory.wrap(uppedContent);
                        }));
                    }
                }
                return super.writeWith(body);
            }

            @Override
            public Mono<Void> writeAndFlushWith(Publisher<? extends Publisher<? extends DataBuffer>> body) {
                return writeWith(Flux.from(body).flatMapSequential(p -> p));
            }
        };
        return chain.filter(exchange.mutate().response(decoratedResponse).build());
    }

    @Override
    public int getOrder() {
        return -2;
    }
}
